#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <syslog.h>

#include <proto.h>

#include "mainconf.h"
#include "conf.h"

struct config_st configure;

static void daemon_exit()
{
	close(configure.send_sd);

	exit(0);
}

static int socket_prepare(int af)
{
	int sd;
	struct ip_mreqn mreq;

	sd = socket(af, SOCK_DGRAM, 0);
	if (sd<0) {
		return -1;
	}
	inet_pton(AF_INET, configure.mgroup, &mreq.imr_multiaddr);
	inet_pton(AF_INET, "0.0.0.0", &mreq.imr_address);
	mreq.imr_ifindex = if_nametoindex(configure.ifname);
	if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, &mreq, sizeof(mreq))<0) {
		close(sd);
		return -1;
	}

	return sd;
}

int
main()
{
	struct chn_entry_st *list;
	int list_size, i;

	openlog(PROJECT_NAME, LOG_PID|LOG_PERROR, configure.log_facility);

	/* 解析配置，生成全局configure */

	configure.send_sd = socket_prepare(AF_INET);

	chdir(configure.working_dir);
	daemon(0, 1);

	if (medialib_get_chnlist(&list, &list_size)) {
		/***/
	}

	if (thr_hoster_create(list, list_size)) {
		/***/
	}

	for (i=0;i<list_size;++i) {
		if (thr_channel_create(list+i)) {
		}
	}

	while (1) pause();

	return 0;
}

